Setup & Autocomplete
Install kubectl
bash
1# macOS (Homebrew)2brew install kubectl3
4# Linux (apt)5sudo apt update && sudo apt install -y kubectl6
7# Verify installation8kubectl version --clientShell Autocomplete
bash
1# Bash2source <(kubectl completion bash)3echo "source <(kubectl completion bash)" >> ~/.bashrc4
5# Zsh6source <(kubectl completion zsh)7echo '[[ $commands[kubectl] ]] && source <(kubectl completion zsh)' >> ~/.zshrc8
9# Fish (requires kubectl 1.23+)10echo 'kubectl completion fish | source' > ~/.config/fish/completions/kubectl.fishUseful Aliases
bash
1alias k=kubectl2complete -o default -F __start_kubectl k # Bash autocomplete for alias3
4alias kx='kubectl config use-context'5alias kn='kubectl config set-context --current --namespace'6alias kga='kubectl get all'7alias kgp='kubectl get pods'8alias kgs='kubectl get svc'9alias kgn='kubectl get nodes'Shorthand Flags
bash
1kubectl -A # Short for --all-namespaces2kubectl -n my-ns # Short for --namespace my-ns3kubectl -o wide # Short for --output wide4kubectl -o yaml # Short for --output yaml5kubectl -w # Short for --watchImportant Paths & Config Files
Kubeconfig & Cluster Configuration
bash
1~/.kube/config # Default kubeconfig file (contexts, clusters, users)2/etc/kubernetes/ # Kubernetes cluster config (on control plane nodes)3/etc/kubernetes/admin.conf # Admin kubeconfig (created by kubeadm)4/etc/kubernetes/manifests/ # Static pod manifests (kube-apiserver, etcd, etc.)5/etc/kubernetes/pki/ # Cluster certificates and keysContainer Runtime Paths
bash
1/var/log/containers/ # Container log files (symlinks)2/var/log/pods/ # Pod log files organized by pod UID3/var/lib/kubelet/ # Kubelet data directory4/var/lib/kubelet/config.yaml # Kubelet configuration5/var/lib/etcd/ # etcd data directory6/var/run/containerd/ # Containerd runtime socketEnvironment Variables
bash
1KUBECONFIG=~/.kube/config # Path to kubeconfig (can be colon-separated list)2KUBECONFIG=~/.kube/config:~/.kube/config2 # Use multiple kubeconfig files3KUBE_EDITOR="nano" # Set editor for kubectl editContext & Cluster Management
View & Switch Context
bash
1kubectl config view # Show merged kubeconfig settings2kubectl config view --raw # Show full config with secrets/certs3kubectl config current-context # Display the current context4kubectl config get-contexts # List all contexts5kubectl config get-contexts -o name # List context names only6kubectl config use-context my-cluster # Switch to a different context7kubectl config set-context --current --namespace=my-ns # Set default namespaceManage Clusters & Users
bash
1kubectl config set-cluster my-cluster --server=https://1.2.3.4:6443 # Add cluster2kubectl config set-cluster my-cluster --proxy-url=http://proxy:8080 # Set proxy3kubectl config set-credentials user1 --username=admin --password=pass # Add user4kubectl config unset users.foo # Delete a user entry5kubectl config delete-context my-context # Delete a contextCluster Info
bash
1kubectl cluster-info # Display master and services addresses2kubectl cluster-info dump # Dump full cluster state to stdout3kubectl cluster-info dump --output-directory=/tmp/cluster-state # Dump to directory4kubectl version # Show client and server versions5kubectl api-versions # List all API versions6kubectl api-resources # List all resource types with shortnames7kubectl api-resources --namespaced=true # Only namespaced resources8kubectl api-resources --namespaced=false # Only cluster-scoped resources9kubectl api-resources --verbs=list,get # Resources supporting list and getNamespaces
Manage Namespaces
bash
1kubectl get namespaces # List all namespaces2kubectl get ns # Short form3kubectl create namespace my-ns # Create a namespace4kubectl delete namespace my-ns # Delete a namespace (and all resources in it!)5kubectl config set-context --current --namespace=my-ns # Set default namespace6kubectl get all -n my-ns # List all resources in a namespace7kubectl get all -A # List all resources across all namespacesCreating & Applying Resources
Apply Manifests (Declarative — Recommended)
bash
1kubectl apply -f manifest.yaml # Create or update resource(s)2kubectl apply -f file1.yaml -f file2.yaml # Apply multiple files3kubectl apply -f ./manifests/ # Apply all manifests in a directory4kubectl apply -f https://example.com/m.yaml # Apply from URL5kubectl diff -f manifest.yaml # Preview changes before applyingCreate Resources (Imperative)
bash
1kubectl create deployment nginx --image=nginx # Create deployment2kubectl create service clusterip my-svc --tcp=80:8080 # Create service3kubectl create namespace my-ns # Create namespace4kubectl create configmap my-config --from-literal=key=value # Create configmap5kubectl create secret generic my-secret --from-literal=pwd=s3cr3t # Create secret6kubectl create job my-job --image=busybox -- echo "Hello" # Create job7kubectl create cronjob my-cj --image=busybox --schedule="*/5 * * * *" -- echo "Hi" # Create cronjobDry Run & Generate YAML
bash
1kubectl create deployment nginx --image=nginx --dry-run=client -o yaml # Generate YAML without creating2kubectl run nginx --image=nginx --dry-run=client -o yaml > pod.yaml # Generate pod YAML to file3kubectl explain pods # Get documentation for pod manifest fields4kubectl explain pods.spec.containers # Explain a specific fieldViewing & Inspecting Resources
Get Resources (Basic)
bash
1kubectl get pods # List pods in current namespace2kubectl get pods -A # List pods in all namespaces3kubectl get pods -o wide # List pods with extra info (node, IP)4kubectl get pods -o yaml # Output as YAML5kubectl get pods -o json # Output as JSON6kubectl get pods -o name # Output resource names only7kubectl get pods --show-labels # Show labels for all pods8kubectl get pods -w # Watch for changes in real-time9kubectl get all # List all resource types in namespaceGet Specific Resource Types
bash
1kubectl get nodes # List nodes2kubectl get nodes -o wide # Nodes with extra info3kubectl get deployments # List deployments4kubectl get svc # List services5kubectl get ep # List endpoints6kubectl get rs # List replicasets7kubectl get ds # List daemonsets8kubectl get sts # List statefulsets9kubectl get jobs # List jobs10kubectl get cronjobs # List cronjobs11kubectl get pv # List persistent volumes12kubectl get pvc # List persistent volume claims13kubectl get configmap # List configmaps14kubectl get secret # List secrets15kubectl get ingress # List ingresses16kubectl get events --sort-by=.metadata.creationTimestamp # Events sorted by time17kubectl events --types=Warning # Warning events onlyDescribe Resources (Detailed View)
bash
1kubectl describe pod my-pod # Detailed info about a pod2kubectl describe node my-node # Detailed info about a node3kubectl describe deployment my-dep # Detailed info about a deployment4kubectl describe svc my-service # Detailed info about a service5kubectl describe pvc my-pvc # Detailed info about a PVCFiltering & Sorting
bash
1kubectl get pods -l app=nginx # Filter by label2kubectl get pods -l 'app in (nginx,redis)' # Filter by label (set-based)3kubectl get pods --field-selector=status.phase=Running # Filter by field4kubectl get pods --sort-by='.status.containerStatuses[0].restartCount' # Sort by restarts5kubectl get services --sort-by=.metadata.name # Sort by name6kubectl get pv --sort-by=.spec.capacity.storage # Sort PVs by capacity7kubectl get node --selector='!node-role.kubernetes.io/control-plane' # Exclude control planeJSONPath & Custom Output
bash
1# Get pod IPs2kubectl get pods -o jsonpath='{.items[*].status.podIP}'3
4# Get node external IPs5kubectl get nodes -o jsonpath='{.items[*].status.addresses[?(@.type=="ExternalIP")].address}'6
7# Custom columns output8kubectl get pods -o custom-columns='NAME:.metadata.name,STATUS:.status.phase,NODE:.spec.nodeName'9
10# Get all images running in a cluster11kubectl get pods -A -o=custom-columns='DATA:spec.containers[*].image'Labels & Annotations
Managing Labels
bash
1kubectl label pods my-pod app=nginx # Add a label2kubectl label pods my-pod app=redis --overwrite # Overwrite a label3kubectl label pods my-pod app- # Remove a label4kubectl get pods -l app=nginx # Select by label5kubectl get pods --show-labels # Show all labelsManaging Annotations
bash
1kubectl annotate pods my-pod description="my app" # Add annotation2kubectl annotate pods my-pod description- # Remove annotationDeployments & Rollouts
Manage Deployments
bash
1kubectl create deployment nginx --image=nginx --replicas=3 # Create with replicas2kubectl get deployments # List deployments3kubectl describe deployment my-dep # Describe deployment4kubectl delete deployment my-dep # Delete deploymentRolling Updates & Rollbacks
bash
1kubectl set image deployment/my-dep nginx=nginx:1.25 # Update image2kubectl rollout status deployment/my-dep # Watch rollout progress3kubectl rollout history deployment/my-dep # View rollout history4kubectl rollout undo deployment/my-dep # Rollback to previous version5kubectl rollout undo deployment/my-dep --to-revision=2 # Rollback to specific revision6kubectl rollout restart deployment/my-dep # Rolling restart7kubectl rollout pause deployment/my-dep # Pause rollout8kubectl rollout resume deployment/my-dep # Resume rolloutScaling
bash
1kubectl scale deployment my-dep --replicas=5 # Scale to 5 replicas2kubectl scale --replicas=3 -f deployment.yaml # Scale from file3kubectl autoscale deployment my-dep --min=2 --max=10 --cpu-percent=80 # Autoscale4kubectl get hpa # List horizontal pod autoscalersServices & Networking
Expose & Manage Services
bash
1kubectl expose deployment my-dep --port=80 --target-port=8080 --type=ClusterIP # ClusterIP2kubectl expose deployment my-dep --port=80 --target-port=8080 --type=NodePort # NodePort3kubectl expose deployment my-dep --port=80 --target-port=8080 --type=LoadBalancer # LoadBalancer4kubectl get svc # List services5kubectl describe svc my-service # Service details6kubectl delete svc my-service # Delete servicePort Forwarding
bash
1kubectl port-forward pod/my-pod 8080:80 # Forward pod port to local2kubectl port-forward svc/my-service 8080:80 # Forward service port to local3kubectl port-forward deploy/my-dep 8080:80 # Forward deployment port to local4kubectl port-forward pod/my-pod 8080:80 --address=0.0.0.0 # Listen on all interfacesDNS & Networking
bash
1# Service DNS format inside the cluster:2# <service-name>.<namespace>.svc.cluster.local3
4# Test DNS resolution from a pod5kubectl run dns-test --image=busybox:1.28 --rm -it -- nslookup my-service.default.svc.cluster.local6
7# Get endpoints for a service8kubectl get endpoints my-servicePods & Containers
Run Pods
bash
1kubectl run nginx --image=nginx # Run a pod2kubectl run nginx --image=nginx -n my-ns # Run in specific namespace3kubectl run debug --image=busybox:1.28 -it --rm -- sh # Temporary interactive pod4kubectl run nginx --image=nginx --dry-run=client -o yaml # Generate YAML onlyExec Into Containers
bash
1kubectl exec my-pod -- ls / # Run command in pod2kubectl exec my-pod -- cat /etc/config/app.conf # Read a file3kubectl exec -it my-pod -- /bin/sh # Interactive shell4kubectl exec -it my-pod -- /bin/bash # Interactive bash shell5kubectl exec my-pod -c my-container -- ls / # Specific container (multi-container)Copy Files
bash
1kubectl cp /tmp/file.txt my-pod:/tmp/file.txt # Local → Pod2kubectl cp my-pod:/tmp/file.txt /tmp/file.txt # Pod → Local3kubectl cp /tmp/file.txt my-ns/my-pod:/tmp/file.txt # With namespace4kubectl cp /tmp/file.txt my-pod:/tmp/file.txt -c my-container # Specific containerPod Management
bash
1kubectl delete pod my-pod # Delete a pod2kubectl delete pod my-pod --now # Delete immediately (no grace period)3kubectl delete pod my-pod --grace-period=0 --force # Force delete4kubectl delete pods -l app=nginx # Delete by label5kubectl -n my-ns delete pod,svc --all # Delete all pods and servicesLogs & Debugging
Viewing Logs
bash
1kubectl logs my-pod # Pod logs (stdout)2kubectl logs my-pod --previous # Logs from previous container instance3kubectl logs my-pod -c my-container # Specific container logs4kubectl logs -f my-pod # Stream/follow logs5kubectl logs -f my-pod -c my-container # Stream specific container logs6kubectl logs my-pod --tail=100 # Last 100 lines7kubectl logs my-pod --since=1h # Logs from last hour8kubectl logs my-pod --since=5m # Logs from last 5 minutes9kubectl logs my-pod --timestamps # Show timestamps10kubectl logs -l app=nginx # Logs from all pods with label11kubectl logs -l app=nginx --all-containers # All containers with label12kubectl logs deploy/my-dep # Logs from deployment13kubectl logs job/my-job # Logs from a jobDebugging Pods
bash
1kubectl describe pod my-pod # Full pod details, events, conditions2kubectl get pod my-pod -o yaml # Full YAML manifest3kubectl get events --field-selector involvedObject.name=my-pod # Events for specific pod4
5# Debug with ephemeral container6kubectl debug my-pod -it --image=busybox:1.28 # Attach debug container to pod7kubectl debug my-pod -it --image=nicolaka/netshoot # Network debugging tools8kubectl debug node/my-node -it --image=busybox:1.28 # Debug a nodeTroubleshooting Checklist
bash
1# Pod stuck in Pending?2kubectl describe pod my-pod # Check Events section for scheduling issues3kubectl get events -n my-ns # Check namespace events4
5# Pod in CrashLoopBackOff?6kubectl logs my-pod --previous # Check previous container's logs7kubectl describe pod my-pod # Check exit code and events8
9# Service not reachable?10kubectl get endpoints my-service # Check if endpoints are populated11kubectl describe svc my-service # Verify selector matches pod labels12kubectl get pods -l <selector-from-svc> # Confirm matching pods exist13
14# Check resource usage15kubectl top pods # CPU/Memory per pod (requires metrics-server)16kubectl top nodes # CPU/Memory per node17kubectl top pod my-pod --containers # Per-container metricsConfigMaps & Secrets
ConfigMaps
bash
1kubectl create configmap my-config --from-literal=key1=value1 --from-literal=key2=value22kubectl create configmap my-config --from-file=config.txt # From file3kubectl create configmap my-config --from-file=configs/ # From directory4kubectl create configmap my-config --from-env-file=.env # From env file5kubectl get configmaps # List configmaps6kubectl describe configmap my-config # View configmap details7kubectl get configmap my-config -o yaml # View as YAML8kubectl delete configmap my-config # Delete configmapSecrets
bash
1kubectl create secret generic my-secret --from-literal=password=s3cr3t2kubectl create secret generic my-secret --from-file=ssh-key=~/.ssh/id_rsa # From file3kubectl create secret tls my-tls --cert=tls.crt --key=tls.key # TLS secret4kubectl get secrets # List secrets5kubectl describe secret my-secret # View metadata (not data)6kubectl get secret my-secret -o yaml # View with base64-encoded data7kubectl get secret my-secret -o jsonpath='{.data.password}' | base64 -d # Decode a secret value8kubectl delete secret my-secret # Delete secretPersistent Storage
PersistentVolumes & PersistentVolumeClaims
bash
1kubectl get pv # List persistent volumes2kubectl get pvc # List persistent volume claims3kubectl describe pv my-pv # Describe PV4kubectl describe pvc my-pvc # Describe PVC5kubectl delete pvc my-pvc # Delete PVC6kubectl get storageclass # List storage classes7kubectl describe storageclass my-sc # Describe storage classNode Management
View & Manage Nodes
bash
1kubectl get nodes # List all nodes2kubectl get nodes -o wide # Nodes with IPs, OS, kernel info3kubectl describe node my-node # Full node details4kubectl top node # Node resource usage5kubectl top node my-node # Specific node usageMaintenance & Scheduling
bash
1kubectl cordon my-node # Mark node as unschedulable2kubectl uncordon my-node # Mark node as schedulable again3kubectl drain my-node # Evict pods for maintenance4kubectl drain my-node --ignore-daemonsets --delete-emptydir-data # Force drainTaints & Tolerations
bash
1kubectl taint nodes my-node key=value:NoSchedule # Add taint2kubectl taint nodes my-node key=value:NoSchedule- # Remove taint3
4# View existing taints5kubectl get nodes -o='custom-columns=NodeName:.metadata.name,TaintKey:.spec.taints[*].key,TaintValue:.spec.taints[*].value,TaintEffect:.spec.taints[*].effect'Resource Updates & Patching
Edit Resources
bash
1kubectl edit deployment my-dep # Open in default editor2KUBE_EDITOR="nano" kubectl edit svc my-svc # Use specific editorUpdate Resources
bash
1kubectl set image deployment/my-dep nginx=nginx:1.25 # Update container image2kubectl set resources deployment/my-dep -c=nginx --limits=cpu=200m,memory=256Mi # Set resource limits3kubectl replace -f manifest.yaml # Replace resource from file4kubectl replace --force -f manifest.yaml # Force replace (delete + recreate)Patch Resources
bash
1# Strategic merge patch2kubectl patch deployment my-dep -p '{"spec":{"replicas":3}}'3
4# JSON patch5kubectl patch pod my-pod --type='json' -p='[{"op":"replace","path":"/spec/containers/0/image","value":"nginx:1.25"}]'6
7# Patch a node (mark unschedulable)8kubectl patch node my-node -p '{"spec":{"unschedulable":true}}'9
10# Patch scale subresource11kubectl patch deployment my-dep --subresource='scale' --type='merge' -p '{"spec":{"replicas":5}}'Deleting Resources
Delete Commands
bash
1kubectl delete -f manifest.yaml # Delete from file2kubectl delete pod my-pod # Delete specific pod3kubectl delete pod my-pod --now # No grace period4kubectl delete pod,svc my-pod my-svc # Delete pod and service5kubectl delete pods,services -l app=nginx # Delete by label6kubectl -n my-ns delete pod,svc --all # Delete all in namespace7kubectl delete namespace my-ns # Delete entire namespaceRBAC & Security
View Roles & Bindings
bash
1kubectl get roles -A # List roles in all namespaces2kubectl get clusterroles # List cluster-wide roles3kubectl get rolebindings -A # List role bindings4kubectl get clusterrolebindings # List cluster role bindings5kubectl describe clusterrole admin # Describe a cluster role6kubectl get serviceaccount -A # List service accountsCheck Permissions
bash
1kubectl auth can-i create pods # Check if you can create pods2kubectl auth can-i '*' '*' # Check if you have full access3kubectl auth can-i create pods --as=user1 # Check as another user4kubectl auth can-i list secrets --as=system:serviceaccount:my-ns:my-sa # Check as service account5kubectl auth whoami # Show current authentication infoResource Quotas & Limits
View Resource Usage
bash
1kubectl top pods # Pod CPU/Memory (requires metrics-server)2kubectl top pods -A # All namespaces3kubectl top pods --sort-by=cpu # Sort by CPU4kubectl top pods --sort-by=memory # Sort by memory5kubectl top nodes # Node CPU/Memory6kubectl top pod my-pod --containers # Per-container metricsQuotas & Limits
bash
1kubectl get resourcequotas -A # List resource quotas2kubectl describe resourcequota my-quota # View quota details3kubectl get limitranges -A # List limit ranges4kubectl describe limitrange my-limits # View limit range detailsOutput Formatting
Common Output Flags
| Flag | Description |
|---|---|
-o yaml | YAML format |
-o json | JSON format |
-o wide | Extra details (node, IP) |
-o name | Resource names only |
-o jsonpath='{...}' | Extract specific fields |
-o custom-columns=... | Custom table columns |
-o go-template=... | Go template formatting |
--sort-by=... | Sort by a field |
--no-headers | Omit column headers |
Verbosity Levels
| Flag | Description |
|---|---|
--v=0 | Always visible to operators |
--v=1 | Reasonable default |
--v=2 | Useful steady state info (recommended) |
--v=4 | Debug level |
--v=6 | Display requested resources |
--v=7 | Display HTTP request headers |
--v=9 | Full HTTP request content |
Common Resource Shortnames
| Short | Full Resource |
|---|---|
po | pods |
svc | services |
deploy | deployments |
rs | replicasets |
ds | daemonsets |
sts | statefulsets |
ns | namespaces |
no | nodes |
pv | persistentvolumes |
pvc | persistentvolumeclaims |
cm | configmaps |
sa | serviceaccounts |
ing | ingresses |
ep | endpoints |
sc | storageclasses |
hpa | horizontalpodautoscalers |
cj | cronjobs |
netpol | networkpolicies |